package com.hyj.app.demo;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class SubProcessActivity extends AppCompatActivity {
    private String processName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);

        setNewIntent(getIntent());
    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        setNewIntent(intent);
//    }

    protected void setNewIntent(Intent intent) {

        // 获取进程名
        processName = intent.getStringExtra("process_name");
        if (processName == null) processName = "default_sub";

        // 显示内容
        ((TextView) findViewById(R.id.tv_content)).setText(intent.getStringExtra("text"));
        setTitle(processName);

        // 通知进程创建
//        notifyProcessStatus(true);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        notifyProcessStatus(false);
    }

    private void notifyProcessStatus(boolean isCreated) {
        bindService(new Intent(this, ProcessManagerService.class), new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                try {
                    ProcessObserver observer = ProcessObserver.Stub.asInterface(service);
                    if (isCreated) {
                        observer.onProcessCreated(processName);
                    } else {
                        observer.onProcessDestroyed(processName);
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                unbindService(this);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {}
        }, BIND_AUTO_CREATE);
    }
}